package com.tecnap.app.database;

import com.tecnap.app.ConfigEntity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

/**
 * This class provides a connector between
 * Application and Database Table "config"
 */
public class ConfigDataSource extends DataSource {
	
	public ConfigDataSource(Context context) {
		super(context);
	}

	/**
	 * Execute query to find associated config value for a certain key
	 * and return the object representation of it
	 * (see: com.tecnap.app.ConfigEntity)
	 * 
	 * @param key
	 * @return value
	 */
	public ConfigEntity getConfig(String key) {
		Cursor cursor = database.query(
				DatabaseHelper.TABLE_CONFIG,
				null, "key = ?",	new String[] { key },
				null, null,	null );
		
		if (cursor.moveToFirst())
			return cursorToConfig(cursor);
		
		return null;
	}
	
	/**
	 * Create or Update a new config tuple into DB
	 * @param key
	 * @param value
	 */
	public void setConfig(String key, String value) {
		ConfigEntity config = new ConfigEntity(key, value);
		setConfig(config);
	}
	
	/**
	 * Create or Update a new config tuple into DB
	 * @param config
	 */
	public void setConfig(ConfigEntity config) {
		// Values container
		ContentValues values = new ContentValues();
		values.put("value", config.getValue());
		
		// Check if the tuple already exists
		if ( getConfig(config.getKey()) == null ) {
			// Then create the tuple
			values.put("key", config.getKey());
			
			database.insert(DatabaseHelper.TABLE_CONFIG, null, values);
		} else {
			// Else update it
			database.update(DatabaseHelper.TABLE_CONFIG, values, "key = ?",
					new String[] { config.getKey() });
			
		}
	}

	/**
	 * Return a new ConfigEntity object from a cursor
	 * 
	 * @param cursor
	 * @return ConfigEntity
	 */
	private ConfigEntity cursorToConfig(Cursor cursor) {
		return new ConfigEntity( cursor.getString(0), cursor.getString(1) );
	}
	
}